import { areaSelectTreeList, SDTBAreaMappingTreeVo } from '@/api/area.api';
import { TreeSelectOption } from 'naive-ui';
import { ref } from 'vue';

/**是否需要最上级 */
const need_top = true;

const areaData = ref<SDTBAreaMappingTreeVo[]>([]);

const areaSelectList = ref<TreeSelectOption[]>([]);

const hasAreaData = () => !!areaData && areaData.value.length;

const hasAreaSelectList = () => !!areaSelectList && areaSelectList.value.length;

export function useArea() {
  const initData = async () => {
    try {
      if (!hasAreaData()) {
        await getAreaDataByApi();
      }
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * 通过接口获取区划树形列表
   * @returns
   */
  const getAreaDataByApi = async () => {
    try {
      const res = await areaSelectTreeList();
      console.log('区划', res);
      areaData.value = res.data || [];
    } catch (error) {
      console.log(error);
    }
    return areaData.value;
  };

  /**
   * 获取区划树形选择器数据列表，可直接使用
   * @returns
   */
  const getAreaSelectList = (VITE_AREA_CODE?: string): TreeSelectOption[] => {
    if (hasAreaSelectList() && (!VITE_AREA_CODE || VITE_AREA_CODE === areaSelectList.value[0].key))
      return areaSelectList.value;
    if (!hasAreaData()) return [];
    const __item = VITE_AREA_CODE ? getAreaInfoByCode(VITE_AREA_CODE) : undefined;
    const data: SDTBAreaMappingTreeVo[] = __item ? [__item] : areaData.value;
    if (!data || !data.length) return [];
    const _data: SDTBAreaMappingTreeVo[] = need_top
      ? data
      : data.reduce((t, c) => {
          return [...t, ...(c.children || [])];
        }, []);
    const deep = (data: SDTBAreaMappingTreeVo[]) => {
      return data.map((item) => ({
        label: item.areaName,
        key: item.areaCode,
        children: item.children && item.children.length ? deep(item.children) : undefined,
      }));
    };
    areaSelectList.value = deep(_data);
    return areaSelectList.value;
  };

  /**
   * 通过区划编码获取区划信息
   * @param code 区划编码
   * @returns 区划信息
   */
  const getAreaInfoByCode = (
    code: SDTBAreaMappingTreeVo['areaCode']
  ): SDTBAreaMappingTreeVo | undefined => {
    if (!code || !hasAreaData()) return undefined;
    let res: SDTBAreaMappingTreeVo | undefined = undefined;
    const deep = (data: SDTBAreaMappingTreeVo[]) => {
      return data.some((item) => {
        if (item.areaCode === code) {
          res = item;
          return true;
        }
        if (item.children && item.children.length) return deep(item.children);
      });
    };
    deep(areaData.value);
    return res;
  };

  /**
   * 通过区划编码获取地址
   * @param code 区划编码
   * @returns 地址 例如重庆市渝北区鸳鸯街道
   */
  const getAddressByCode = (code: SDTBAreaMappingTreeVo['areaCode']) => {
    if (!code || !hasAreaData()) return '';
    const res: string[] = [];
    const deep = (data: SDTBAreaMappingTreeVo[]) => {
      return data.some((item) => {
        if (item.areaCode === code) {
          res.push(item.areaName || '');
          return true;
        }
        if (item.children && item.children.length) {
          const flag = deep(item.children);
          flag && res.push(item.areaName || '');
          return false;
        }
      });
    };
    deep(areaData.value);
    let str = '';
    res.reverse().forEach((i) => (str += i));
    return str;
  };

  initData();

  return {
    areaData,
    areaSelectList,
    hasAreaData,
    hasAreaSelectList,
    getAreaSelectList,
    getAreaInfoByCode,
    getAddressByCode,
  };
}
